<?php
namespace app\index\controller;
use app\index\logic\Sign;
use app\index\model\Category;
use app\index\model\Question;
use app\index\service\Category as CategoryService;
use think\Controller;
use think\Db;

class Index extends Common
{
    public function index()
    {
        $where = [];

        if(input('cid')){
            $where['t1.cid'] = input('cid');
        }

        if(input('status')!==null){
            $where['t1.status'] = input('status');
        }

        if(input('is_jing')){
            $where['t1.is_jing'] = input('is_jing');
        }

        if(!$where){

            $top = Db::table('fly_question')
            ->alias('t1')
            ->field('t1.*,t2.username,t2.face,t2.level,t3.cname')
            ->join('fly_user t2','t1.uid = t2.uid')
            ->join('fly_category t3','t1.cid = t3.cid')
            ->where('is_top','1')
            ->cache(true,3600)
            ->select();

            $this->assign('top',$top);
        }


        $all= Db::table('fly_question')
        ->alias('t1')
        ->field('t1.*,t2.username,t2.face,t2.level,t3.cname')
        ->join('fly_user t2','t1.uid = t2.uid')
        ->join('fly_category t3','t1.cid = t3.cid')
        ->where($where)
        ->cache(true,120)
        ->order('t1.ctime desc')
        ->paginate(5);


        if(cache('weekhot')){
            $weekHot = cache('weekhot');
        }else{
            $weekHot= Db::table('fly_reply')
            ->alias('t1')
            ->field('count(*) cn,t2.username,t2.face,t2.uid')
            ->join('fly_user t2','t1.uid = t2.uid')
            ->where('t1.ctime','>',strtotime('-7 days'))
            ->group('t1.uid')
            ->order('cn desc')
            ->limit(10)
            ->select();

            cache('weekhot',$weekHot,7200);
        }

    	$hotques = (new Question)->order('reply_num desc')->limit(10)->cache(true,3600)->select();

    	$cates = CategoryService::getCateData();

    	$this->assign('cates',$cates);
        $this->assign('hotques',$hotques);
        $this->assign('weekHot',$weekHot);
        
        $this->assign('all',$all);

        $signInfo = Sign::getInfo();

        $this->assign('signInfo',$signInfo);
        
        if(input('cid')){
            $this->assign('title',Category::get(input('cid'))->cname);
        }else{
            $this->assign('title',"一个所有老司机在的地方");
        }
        
        return $this->fetch();
    }
}
